package com.aos.erp.common.web.filter;

import com.aos.erp.common.web.AuthorizationContext;
import com.aos.erp.common.web.wrapper.RequestWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class TokenFilter extends OncePerRequestFilter {

    // 网关需要判断你的认证信息，必须存放在Header中
    public static final String GATEWAY_AUTHORIZATION="Authorization";
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        RequestWrapper requestWrapper = new RequestWrapper(request);

        String authorization = getHeader(request, GATEWAY_AUTHORIZATION);

        if (StringUtils.isNotBlank(authorization)) {
            AuthorizationContext.set(authorization);
        }

        //由前端传入userId
        // todo 后期可考虑根据authorization在redis中获取 userId，防止前段篡改用户标识
        String userId = getHeader(request, "currentUserId");
        if (StringUtils.isNotBlank(userId)) {
            requestWrapper.addParameter("currentUserId", userId);
        }

        filterChain.doFilter(requestWrapper, response);
    }

    public String getHeader(HttpServletRequest request, String param) {
        //先从header中获取
        String header = request.getHeader(param);

        return header;
    }

}
